<?php

class CS_Config extends CS_Core
{

	public static $instance;

	public static function getInstance()
	{
		$class = __CLASS__;
		
		if(!isset(self::$instance[$class]))
		{
			self::$instance[$class] = new $class;
		}

		return self::$instance[$class];
	}
	
	public static function write($key, $value)
	{
		$_this = self::getInstance();

		if (!is_array($key)) {
			$key = array($key => $value);
		}

		foreach ($key as $name => $value) {
			if (strpos($name, '.') === false) {
				$_this->{$name} = $value;
			} else {
				$names = explode('.', $name, 4);
				switch (count($names)) {
					case 2:
						$_this->{$names[0]}[$names[1]] = $value;
					break;
					case 3:
						$_this->{$names[0]}[$names[1]][$names[2]] = $value;
						break;
					case 4:
						$names = explode('.', $name, 2);
						if (!isset($_this->{$names[0]})) {
							$_this->{$names[0]} = array();
						}

						$list = $_this->{$names[0]};
						$path = $names[1];
						$data = $value;
						if (!is_array($path)) {
							$path = explode('.', $path);
						}
						$_list =& $list;

						foreach ($path as $i => $key) {
							if (is_numeric($key) && intval($key) > 0 || $key === '0') {
								$key = intval($key);
							}
							if ($i === count($path) - 1) {
								$_list[$key] = $data;
							} else {
								if (!isset($_list[$key])) {
									$_list[$key] = array();
								}
								$_list =& $_list[$key];
							}
						}
						$_this->{$names[0]} = $list;
					break;
				}
			}
		}
	}

	public static function read($key)
	{
		$_this = self::getInstance();

		if (strpos($key, '.') !== false) {
			$names = explode('.', $key, 3);
			$key = $names[0];
		}
		if (!isset($_this->{$key})) {
			return null;
		}
		if (!isset($names[1])) {
			return $_this->{$key};
		}
		switch (count($names)) {
			case 2:
				if (isset($_this->{$key}[$names[1]])) {
					return $_this->{$key}[$names[1]];
				}
			break;
			case 3:
				if (isset($_this->{$key}[$names[1]][$names[2]])) {
					return $_this->{$key}[$names[1]][$names[2]];
				}
				if (!isset($_this->{$key}[$names[1]])) {
					return null;
				}
				//return Set::classicExtract($_this->{$var}[$names[1]], $names[2]);
			break;
		}
		return null;
	}
}
